$(document).ready(function () {
	// 验证码按钮状态
	let emailState = {
		disabled: false,
		text: '发送邮箱验证码',
		time: -1,
		timer: null
	};

	// 验证密码是否一致
	function validatePassword () {
		const password = $('#password').val();
		const repassword = $('#repassword').val();

		if (password !== repassword) {
			alert('两次密码不一致');
			return false;
		}
		return true;
	}

	// 发送验证码
	$('#sendCodeBtn').click(function () {
		const email = $('#email').val();

		if (!email) {
			alert('请先填写邮箱');
			return;
		}

		if (emailState.disabled) return;

		// 模拟发送验证码
		console.log('发送验证码到邮箱:', email);

		// 禁用按钮并开始倒计时
		emailState.disabled = true;
		emailState.time = 60;
		$('#sendCodeBtn').prop('disabled', true).text(`(${emailState.time}S)后重新发送`);

		// 启动倒计时
		emailState.timer = setInterval(function () {
			emailState.time--;
			$('#sendCodeBtn').text(`(${emailState.time}S)后重新发送`);

			if (emailState.time <= 0) {
				clearInterval(emailState.timer);
				emailState.disabled = false;
				$('#sendCodeBtn').prop('disabled', false).text('发送邮箱验证码');
			}
		}, 1000);

		// 模拟API请求
		$.ajax({
			url: '/api/send-email-code',
			method: 'POST',
			data: { email: email },
			success: function () {
				alert('验证码已发送，请注意查收');
			},
			error: function () {
				alert('发送验证码失败');
				clearInterval(emailState.timer);
				emailState.disabled = false;
				$('#sendCodeBtn').prop('disabled', false).text('发送邮箱验证码');
			}
		});
	});

	// 提交修改
	$('#submitBtn').click(function () {
		// 验证必填字段
		const requiredFields = ['email', 'code', 'password', 'repassword'];
		let isValid = true;

		requiredFields.forEach(function (field) {
			if (!$('#' + field).val()) {
				alert('请填写' + $('label[for="' + field + '"]').text());
				isValid = false;
				return false;
			}
		});

		if (!isValid || !validatePassword()) return;

		// 收集表单数据
		const formData = {
			email: $('#email').val(),
			code: $('#code').val(),
			password: $('#password').val(),
			repassword: $('#repassword').val()
		};

		console.log('提交修改密码:', formData);

		// 禁用提交按钮
		$('#submitBtn').prop('disabled', true).text('处理中...');

		// 模拟API请求
		$.ajax({
			url: '/api/reset-password',
			method: 'POST',
			data: formData,
			success: function () {
				alert('密码修改成功');
				// 跳转到首页
				window.location.href = '/';
			},
			error: function (xhr) {
				alert(xhr.responseJSON?.message || '修改密码失败');
			},
			complete: function () {
				$('#submitBtn').prop('disabled', false).text('修改');
			}
		});
	});
});